package com.unicloud.medical.oss.client.autoconfigure;

import com.unicloud.medical.oss.client.properties.OSSGrpcClientProperties;
import com.unicloud.medical.oss.common.constant.OSSPropertiesConstant;
import com.unicloud.medical.oss.service.grpc.OSSServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@ConditionalOnProperty(prefix = OSSPropertiesConstant.OSS_GRPC_CLIENT_PREFIX, name = "enabled", havingValue = "true")
@EnableConfigurationProperties({OSSGrpcClientProperties.class})
public class OSSGrpcClientAutoConfiguration {
    private final OSSGrpcClientProperties grpcClientProperties;
    private ManagedChannel channel;

    public OSSGrpcClientAutoConfiguration(OSSGrpcClientProperties grpcClientProperties) {
        this.grpcClientProperties = grpcClientProperties;
        channel = ManagedChannelBuilder.forAddress(grpcClientProperties.getHost(), grpcClientProperties.getPort())
                .usePlaintext()
                .build();
    }

    @Bean
    public OSSServiceGrpc.OSSServiceBlockingStub ossServiceBlockingStub() {
        return OSSServiceGrpc.newBlockingStub(channel);
    }

    @Bean
    public OSSServiceGrpc.OSSServiceStub ossServiceStub() {
        return OSSServiceGrpc.newStub(channel);
    }

}
